<template>
  <div class="app-container home">
    <query-panel
      :form-data="queryParams"
      @handleQuery="handleQuery"
      :exportSrr="true"
      @exportHand="exportHand"
      label-width="100px"
    >
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="所属节点：" prop="nodeId">
            <treeselect
              class="treeselect"
              style="width: 100%"
              v-model="queryParams.nodeId"
              :options="searchNodeListData"
              :normalizer="normalizer"
              :show-count="true"
              placeholder="请选择"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="资料类型：" prop="documentType">
            <el-select
              v-model="queryParams.documentType"
              style="width: 100%"
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="dict in dict.type.sys_document_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="资料格式：" prop="documentFormatRadio">
            <el-select
              v-model="queryParams.documentFormatRadio"
              style="width: 100%"
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="dict in dict.type.sys_document_format"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="关键字：" prop="documentName">
            <el-input
              v-model="queryParams.documentName"
              placeholder="请输入内容"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="语言：" prop="languages">
            <el-select
              v-model="queryParams.languages"
              placeholder="请选择"
              style="width: 100%"
              @change="handleSearchNodeList"
            >
              <el-option
                v-for="item in languages"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
        <el-button @click="exportHand">导出</el-button>
        </el-col> -->
      </el-row>
    </query-panel>
    <table-panel
      ref="tablePanel"
      align="left"
      table-data="/maintain//maintain/mDocument/list"
      :queryParams="queryParams"
      :columns="columns"
      @onOperate="onOperate"
      :refresh="false"
    >
      <template slot="tableTop">
        <el-button
          class="tableAdd"
          type="primary"
          plain
          size="mini"
          @click="onAdd"
          ><svg-icon icon-class="add_icon" style="width: 18px; height: 16px" />
          新增</el-button
        >
      </template>
      <template #status="{ row }">
        <dict-tag
          :options="dict.type.sys_business_status"
          :value="row.status"
        />
      </template>
      <template #operate="{ row }">
        <el-button
          size="mini"
          type="text"
          class="ordinary-btn"
          @click="onOperate('上架', row)"
          :disabled="row.status != 1 && row.status != 6"
        >
          上架
        </el-button>
        <el-button
          size="mini"
          type="text"
          class="ordinary-btn"
          @click="onOperate('下架', row)"
          :disabled="row.status != 7 && row.status != 9"
        >
          下架
        </el-button>
        <el-button
          size="mini"
          type="text"
          class="ordinary-btn"
          @click="onOperate('预览', row)"
        >
          预览
        </el-button>
        <el-button
          size="mini"
          type="text"
          class="ordinary-btn"
          @click="onOperate('下载', row)"
        >
          下载
        </el-button>
        <el-button
          size="mini"
          type="text"
          class="ordinary-btn"
          @click="onOperate('删除', row)"
          :disabled="row.status != 1"
          ><svg-icon
            icon-class="table-column-delete"
            style="width: 16px; height: 16px"
          />
          删除
        </el-button>
      </template>
    </table-panel>
    <el-dialog
      :title="title"
      :visible.sync="open"
      v-if="open"
      width="458px"
      append-to-body
      :destroy-on-close="true"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-position="left"
        label-width="110px"
        size="mini"
      >
        <el-form-item label="所属节点：" prop="nodeId">
          <treeselect
            v-model="form.nodeId"
            :options="addNodeListData"
            :normalizer="normalizer"
            :show-count="true"
            placeholder="请选择所属节点"
            :disabled="selectDisabled"
          />
        </el-form-item>
        <el-form-item label="资料类型：" prop="documentType">
          <el-select
            v-model="form.documentType"
            style="width: 100%"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="dict in dict.type.sys_document_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="文件格式：" prop="documentFormatRadio">
          <el-select
            style="width: 100%"
            v-model="form.documentFormatRadio"
            placeholder="请选择"
            @change="handleDocumentFormat"
          >
            <el-option
              v-for="item in documentFormatRadio"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="">
          <image-upload
            list-type="picture-card"
            :is-show-tip="false"
            @input="handleImg"
            :value="imgData"
            text="上传文件"
            :limit="limit"
            :storage-type="storageType"
          >
          </image-upload>
        </el-form-item>
        <el-form-item label="语言：" prop="languages">
          <el-radio-group v-model="form.languages" @change="handleAddNodeList">
            <el-radio
              v-for="dict in languages"
              :key="dict.value"
              :label="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="英文名称：" prop="documentNameEn">
          <el-input
            v-model="form.documentNameEn"
            placeholder="请输入资料英文名称"
          />
        </el-form-item>
        <el-form-item label="资料权限:">
          <el-radio-group v-model="nodes1" @change="handleNotes">
            <el-radio label="1" key="1">厂内用户</el-radio>
            <el-radio label="2" key="2">厂外用户</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          size="mini"
          class="tableAdd"
          @click="submitForm"
        >
          确定
        </el-button>
        <el-button
          class="dialogCancel"
          type="primary"
          size="mini"
          @click="open = false"
          >关闭</el-button
        >
      </div>
    </el-dialog>
    <el-dialog
      :title="previewTitle"
      :visible.sync="previewOpen"
      v-if="previewOpen"
      width="1200px"
      append-to-body
      :destroy-on-close="true"
    >
      <div style="height: 800px">
        <template-window :form-data="formData" :template-type="templateType" />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button
          class="dialogCancel"
          type="primary"
          size="mini"
          @click="previewOpen = false"
          >关闭</el-button
        >
      </div>
    </el-dialog>
    <el-dialog
      title="审批人"
      :visible.sync="approverShow"
      width="458px"
      append-to-body
      :destroy-on-close="true"
    >
      <approver ref="approver" />
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          size="mini"
          class="tableAdd"
          @click="submitApprover"
        >
          确定
        </el-button>
        <el-button
          class="dialogCancel"
          type="primary"
          size="mini"
          @click="approverShow = false"
          >关闭</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import TablePanel from "@/components/TablePanel/index.vue";
import QueryPanel from "@/components/QueryPanel/index.vue";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { serachNodeList } from "@/api/nodeManage/node";
import { addData, deleteData, sumbitData } from "@/api/dataManage/index";
import { uploadImg, detailsImg, preview } from "@/api/file/index";
import { Base64 } from "js-base64";
import TemplateWindow from "@/views/components/template/index.vue";
import Approver from "@/views/components/Approver/index.vue";
export default {
  components: {
    TablePanel,
    QueryPanel,
    Treeselect,
    TemplateWindow,
    Approver,
  },
  dicts: ["sys_business_status", "sys_document_type", "sys_document_format"],
  data() {
    return {
      queryParams: {
        nodeId: null,
        documentType: "",
        moduleType: 1, // 模板类型
        languages: "1",
        documentFormatRadio: "",
        documentName: "",
      },
      nodes1: "1",
      searchNodeListData: [],
      addNodeListData: [],
      languages: [
        {
          value: "1",
          label: "中文",
        },
        {
          value: "2",
          label: "英文",
        },
      ],
      columns: [
        {
          field: "documentName",
          label: "文件名称",
        },
        {
          field: "nodeName",
          label: "所属节点",
        },
        {
          field: "status",
          label: "状态",
          slots: { default: "status" },
        },
        {
          label: "操作",
          type: "custom",
          width: "470px",
          slots: { default: "operate" },
        },
      ],
      open: false,
      form: {
        nodeId: null,
        languages: "1",
        moduleType: 1,
        documentType: "",
        documentFormatRadio: "",
        notes: "1",
        documentNameEn: "",
      },
      title: "新增页面",
      rules: {
        nodeId: [
          { required: true, message: "上级节点不能为空", trigger: "change" },
        ],
        languages: [
          { required: true, message: "语言不能为空", trigger: "change" },
        ],
      },
      selectDisabled: false,
      imgData: [],
      documentFormatRadio: [
        {
          value: "",
          label: "其他",
        },
        {
          value: "6",
          label: "360-pic",
        },
        {
          value: "7",
          label: "360-vid",
        },
        {
          value: "4",
          label: "图片",
        },
        {
          value: "5",
          label: "视频",
        },
      ],
      limit: 1,
      storageType: "mongo",
      previewTitle: "",
      previewOpen: false,
      templateType: "",
      formData: null,
      approverShow: false,
      approverPArams: null,
      importOpen: false,
      approverName: []
    };
  },
  mounted() {
    this.init();
    this.handleQuery();
  },
  methods: {
    async init() {
      await this.getTreeselect();
    },
    // 查询
    handleQuery() {
      this.$refs.tablePanel.getTable();
    },
    // 新增按钮
    onAdd() {
      this.imgData = [];
      this.storageType = "mongo";
      this.form = {
        nodeId: null,
        languages: "1",
        moduleType: 1,
        documentType: "",
        documentFormatRadio: "",
        notes: "1",
        documentNameEn: "",
      };
      this.open = true;
      if (this.$refs.form) {
        this.$refs.form.resetFields();
      }
    },
    // 文件回调
    handleImg(str, file) {
      if (typeof str === "boolean") {
        this.form.fileId = "";
      } else {
        this.form.fileId = str.data.fileId;
        this.form.documentName = str.data.name;
      }
    },
    // 资料权限
    handleNotes(data) {
      this.form.notes = data
    },
    // 新增保存
    submitForm() {
      if (Boolean(this.form.fileId) === false) {
        return this.$message.warning("请上传文件！");
      }
      this.$refs["form"].validate((valid) => {
        if (valid) {
          addData(this.form)
            .then((res) => {
              this.$refs.tablePanel.getTable();
              this.$message.success("操作成功！");
              this.open = false;
            })
            .catch((err) => {
              this.$message.error("操作失败！");
            });
        }
      });
    },
    // 表格操作列
    onOperate(type, row) {
      if (type === "删除") {
        this.$confirm("确认删除此条信息？").then(() => {
          deleteData(row.documentId)
            .then((res) => {
              this.$message.success("操作成功！");
              this.$refs.tablePanel.getTable();
            })
            .catch((err) => {
              this.$message.error("操作失败！");
            });
        });
      } else if (type === "上架" || type === "下架") {
        this.approverPArams = {
          ...row,
          actionType: type === "上架" ? 1 : 0,
        };
        sumbitData(this.approverPArams).then((res) => {
          const data = res.data.wfNodeList;
          this.approverName = res.data.wfNodeList;
          let arr = [];
          data.forEach((item) => {
            arr.push({
              label: item,
              personnel: "",
            });
          });
          this.approverShow = true;
          this.$nextTick(() => {
            this.$refs.approver.tableList = arr;
            arr.forEach((item) => {
              this.$refs.approver.candidateUsersList.push(0);
            });
          });
        });
      } else if (type === "下载") {
        detailsImg({ fileId: row.fileId }).then((res) => {
          if (res.data.storeId === null) {
            return this.$confirm(
              "该文件类型不支持直接下载，请在预览页面点击右键进行下载！"
            )
              .then(() => { })
              .catch(() => { });
            window.location.href = res.data.url;
          } else {
            window.location.href =
              process.env.VUE_APP_API_HOST +
              process.env.VUE_APP_BASE_API +
              "/file/mongod-download/" +
              res.data.storeId;
          }
        });
      } else {
        // 预览
        this.formData = row;
        if (row.documentFormat == 7) {
          this.previewTitle = "360视频";
          this.previewOpen = true;
          this.templateType = "360视频";
        } else if (row.documentFormat == 6) {
          this.previewTitle = "360图片";
          this.previewOpen = true;
          this.templateType = "360图片";
        } else if (row.documentFormat == 5) {
          this.previewTitle = "视频";
          this.previewOpen = true;
          this.templateType = "视频";
        } else {
          let params = {
            fileId: row.fileId,
            fileName: row.documentName,
          };
          //   let windowPreview = window.open("", "_blank");
          this.getFileUrl(params).then((res) => {
            if (res.code !== 200) {
              window.close();
              alert(res.msg);
              return;
            }
            window.open(res.preview, "_blank");
            // windowPreview.location.href = res.preview;
          });
        }
      }
    },
    // 查询预览url
    getFileUrl(file) {
      return new Promise((resolve) => {
        preview({ fileId: file.fileId }).then((res) => {
          if (res.code !== 200) {
            return resolve(res);
          }
          let storeId = res.data.storeId;
          let originUrl =
            storeId == null
              ? res.data.url
              : `${process.env.VUE_APP_API_HOST}${process.env.VUE_APP_BASE_API}/file/mongod-download/${storeId}`;
          originUrl += `?fullfilename=${file.fileName}`;
          let fininalUrl =
            process.env.VUE_APP_API_HOST +
            process.env.VUE_APP_BASE_API +
            "/kk-preview/onlinePreview?url=" +
            Base64.encode(originUrl);
          resolve({
            code: 200,
            downloadUrl: originUrl,
            preview: fininalUrl,
          });
        });
      }).catch((err) => {
        resolve({
          code: 500,
          msg: "服务器错误",
        });
      });
    },
    handleSearchNodeList(data) {
      serachNodeList({ moduleType: 1, languages: data }).then((res) => {
        this.searchNodeListData = res.rows;
      });
    },
    handleAddNodeList(data) {
      serachNodeList({ moduleType: 1, languages: data }).then((res) => {
        this.addNodeListData = res.rows;
      });
    },
    getTreeselect() {
      serachNodeList({ moduleType: 1, languages: 1 }).then((res) => {
        this.searchNodeListData = res.rows;
        this.addNodeListData = res.rows;
      });
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children === null) {
        delete node.children;
      }
      return {
        id: node.nodeId,
        label: node.nodeName,
        children: node.children,
      };
    },
    // 文件格式
    handleDocumentFormat(key) {
      if (Boolean(key) === false) {
        this.limit = 1;
        this.storageType = "mongo";
      } else {
        this.limit = 1;
        this.storageType = "local";
      }
    },
    // 提交审批人
    submitApprover() {
      for (let i = 0; i < this.$refs.approver.candidateUsersList.length; i++) {
        if (!this.$refs.approver.candidateUsersList[i]) {
          return this.$message({
            type: 'error',
            message: '请填写' + this.approverName[i]
          })
        }
      }
      this.approverPArams.candidateUsersList =
        this.$refs.approver.candidateUsersList;
      sumbitData(this.approverPArams).then((res) => {
        this.$message.success("操作成功！");
        this.approverShow = false;
        this.$refs.tablePanel.getTable();
      });
    },
    // 数据导出
    exportHand() {
      this.download('maintain//maintain/mDocument/export', {
        ...this.queryParams
      }, `job_${new Date().getTime()}.xlsx`)
    }
  },
};
</script>

<style scoped lang="scss">
::v-deep .cell {
  span {
    font-size: 16px;
  }
  .ordinary-btn {
    width: 80px;
    height: 32px;
    border: 1px solid #dcdcdc;
    font-size: 16px;
    span {
      color: #333333e6;
    }
  }
}
</style>